<template>
  <div class="login-form" v-show="getShow">
    <LoginFormTitle v-show="getShow"  class="enter-x"/>
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef" v-show="getShow">
      <FormItem name="account" class="enter-x">
        <Input size="large" v-model:value="formData.account" :placeholder="t('sys.login.userName')" />
      </FormItem>
      <FormItem name="password" class="enter-x">
        <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
        />
      </FormItem>
      <ARow class="enter-x">
        <ACol :span="12">
          <FormItem>
            <!-- No logic, you need to deal with it yourself -->
            <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
            </Checkbox>
          </FormItem>
        </ACol>
        <ACol :span="12">
          <FormItem :style="{ 'text-align': 'right' }">
            <!-- No logic, you need to deal with it yourself -->
            <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
              {{ t('sys.login.forgetPassword') }}
            </Button>
          </FormItem>
        </ACol>
      </ARow>

      <FormItem class="enter-x">
        <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
        </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
      </FormItem>
      <ARow class="enter-x">
        <ACol :xs="24" :md="8">
          <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
          </Button>
        </ACol>
        <ACol :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
          <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
          </Button>
        </ACol>
        <ACol :md="8" :xs="24">
          <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
          </Button>
        </ACol>
      </ARow>
      <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>

      <div class="flex justify-evenly enter-x" :class="`vben-login-sign-in-way`">
        <GithubFilled />
        <WechatFilled />
        <AlipayCircleFilled />
        <GoogleCircleFilled />
        <TwitterCircleFilled />
      </div>
    </Form>
  </div>
</template>
<script lang="ts">
import LoginFormTitle from "./LoginFormTitle.vue";
import { Options, prop, Vue } from "vue-class-component";
import { defineComponent,ref, reactive ,watchEffect,watch,unref, computed} from "vue";
import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
import { Checkbox, Form, Input, Row, Col, Button, Divider } from 'ant-design-vue';
import { useI18n } from '@/locales/useI18n';
import {
  GithubFilled,
  WechatFilled,
  AlipayCircleFilled,
  GoogleCircleFilled,
  TwitterCircleFilled,
} from '@ant-design/icons-vue';

import { useMessage } from '@/hooks/web/useMessage';
//VueUse是一个Vue Composition API实用程序的集合
import { onKeyStroke } from '@vueuse/core';

import { post,get } from '../../../net/netMethod.js';

import { useLoginStoreWithOut } from '@/store/modules/login';
import { useInfoStoreWithOut } from '@/store/modules/user';
import  RSAUtils from '@/security.js';

import { useRouter } from 'vue-router';
  
export default defineComponent({
  components: {
    LoginFormTitle,
    Form,
    FormItem: Form.Item,
    Input,
    InputPassword: Input.Password,
    Checkbox,
    Button,
    [Col.name]: Col,
    [Row.name]: Row,
    Divider,
    GithubFilled,
    WechatFilled,
    AlipayCircleFilled,
    GoogleCircleFilled,
    TwitterCircleFilled,
},
setup: (props, context) => {
  console.log("setup ok!");
  const loginStore = useLoginStoreWithOut();
  const userStore = useInfoStoreWithOut();
  const { t } = useI18n();
  // 信息提示框
  const { notification } = useMessage();
  // 获取登录状态
  const { setLoginState, getLoginState } = useLoginState();

  // 设置表单校验规则
  const { getFormRules } = useFormRules();
  // 路由
  const router = useRouter();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);

  const getShow = computed(() => {
    var r = unref(getLoginState) === LoginStateEnum.LOGIN
    return r;
  });
  const formData = reactive({
    account: 'vben',
    password: '123456',
  });
  const { validForm } = useFormValid(formRef);

  // 监听Enter键
  onKeyStroke('Enter', handleLogin);

  function postLogin(){

    console.log(loginStore.$state.publicKey)
    console.log(loginStore.$state.publicKey.uuid)

    //var modules = "dc17ad60898e3d30fcbac9a1b0743675820cb48b5c32d38a4e34f86df04f3002d94e22c214763859802c827098a365cba3bdbe33d4addde5dbf80b5f50be2e68bea1ec9404cadfc115d9ba481e831fd7cfc17324993ad94cfae30726fc0b2cecf369ff47aa032b106c5559192771d1eb7a4029f5a7b7d4770a9f76bc0eccebdf";
    //var publicKey = RSAUtils.getKeyPair( loginStore.$state.publicKey.modulus,loginStore.$state.publicKey.modulus,loginStore.$state.publicKey.publicExponent)
    var publicKey = RSAUtils.getKeyPair( "10001","10001",loginStore.$state.publicKey.modulus)
    var pwd = RSAUtils.encryptedTobase64(publicKey, formData.password)
    var url ='login'
    post(null,url,{
      password: pwd,
      userName: formData.account
    }).then(result => {
      console.log(result)
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: `,
        duration: 3,
      });
      userStore.setUserData(result['resultData'])
      var routerData = {
        name: 'Work',
        params: { resultData:[]},
        query: {}
      }
      router.push(routerData);
    }).catch(e => {
      loginStore.setPublic(false, {encoded:'',modulus:'',publicExponent:'',uuid:''})
    });
  }

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;

      if(!loginStore.hasPublicKey){
        // 获取公钥
        var url ='/api/uua/oauth/rsa-public-key'
        post(null,url,{
        }).then(result => {
          console.log(result)
          loginStore.setPublic(true,result.resultData)
          postLogin()
        })
      }else{
        postLogin()
      }

      // const userInfo = await userStore.login(
      //   toRaw({
      //     password: data.password,
      //     username: data.account,
      //   })
      // );
      
    } finally {
      loading.value = false;
    }
  }

  const returnInfo = reactive({
    t,
    getShow,
    formData,
    loading,
    rememberMe,
    formRef,
    handleLogin,
    getFormRules,
    setLoginState,
    LoginStateEnum, // 状态
  })
  return returnInfo;
},
})
</script>
<style scoped>
.ant-form{
  padding: 20px;
  background-color: white;
}
.ant-form >>> .ant-col {
  width: 100% !important;
}
.ant-form >>> .ant-btn-link{
    font-weight: bold;
    text-decoration: underline;
}
.ant-form >>> .ant-btn-primary{
  background-color: #1da31d;
  border-color: #1da31d;
}
.ant-form >>> .ant-btn-primary:hover{
  background-color: #6dd46d;
  border-color: #1da31d;
  font-weight: bold;
}
.ant-form >>> .ant-divider-horizontal.ant-divider-with-text-center{
  margin: 8px;
}
.login-form {
  width: 50%;
  min-width: 300px;
  height: 50vh;
  margin: auto;
  margin-top: 5%;
  /* background-color: #fff; */
  font-size: 1.3em;
  background-color: white;
  
}
.login-form h2 {
  font-weight: 900;
  padding-left: 20px;
  padding-top:10px;
  margin: 0em;
}

</style>